package com.xlh.wjdcserver.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.context.BaseContext;
import com.common.exception.FileException;
import com.common.exception.UserException;
import com.common.property.JwtProperty;
import com.common.result.Result;
import com.common.util.JwtUtil;
import com.property.dto.*;
import com.property.entity.User;
import com.property.vo.RoleVO;
import com.property.vo.UserLoginVO;
import com.property.vo.UserVO;
import com.xlh.wjdcserver.mapper.UserMapper;
import com.xlh.wjdcserver.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private JwtProperty jwtProperty;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", userLoginDTO.getName());
        Long selectCount = baseMapper.selectCount(queryWrapper);
        if (selectCount == 0) {
            throw new UserException("用户不存在");
        }

        User user = baseMapper.selectOne(queryWrapper);
        if(!user.getPassword().equals(userLoginDTO.getPassword()))
        {
            throw new UserException("密码错误");
        }
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtil.copyProperties(user, userLoginVO);
        Map<String, Object> claims = new HashMap<>();
        claims.put("userid", user.getId());
        String token = JwtUtil.createJWT(jwtProperty.getAdminSecretKey(), jwtProperty.getAdminTtl(), claims);
        userLoginVO.setToken(token);

        String key = "login:token:" + user.getId();
        redisTemplate.opsForValue().set(key, token, jwtProperty.getAdminTtl(), TimeUnit.MILLISECONDS);

        return userLoginVO;
    }

    @Override
    public UserLoginVO qlogin(UserQLoginDTO userQLoginDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", userQLoginDTO.getName());
        Long selectCount = baseMapper.selectCount(queryWrapper);
        if (selectCount == 0) {
            throw new UserException("用户不存在");
        }

        User user = baseMapper.selectOne(queryWrapper);
        if(!user.getPassword().equals(userQLoginDTO.getPassword()))
        {
            throw new UserException("密码错误");
        }

        // 判断用户所在的物业公司是否与问卷一致
        List<String> qids = baseMapper.checkQid(user.getCommId());
        if(!qids.contains(userQLoginDTO.getQid()))
        {
            throw new UserException("您所在小区未有问卷需要填写");
        }
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtil.copyProperties(user, userLoginVO);

        return userLoginVO;
    }

    @Override
    public UserVO center(String userId) {
        if (userId == null)
        {
            throw new UserException("用户id不能为空");
        }
        User user = baseMapper.selectById(userId);
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public void updateUser(UserDTO userDTO) {
        User user = new User();
        BeanUtil.copyProperties(userDTO, user);
        baseMapper.updateById(user);
    }

    @Override
    public void updatePassword(UserPwdDTO userPwdDTO) {
        String currentId = BaseContext.getCurrentId();
        User user = baseMapper.selectById(currentId);
        if(!user.getPassword().equals(userPwdDTO.getOldPassword()))
        {
            throw new UserException("旧密码错误");
        }
        if (userPwdDTO.getNewPassword().equals(userPwdDTO.getOldPassword()))
        {
            throw new UserException("新密码不能与旧密码相同");
        }
        if (!userPwdDTO.getNewPassword().equals(userPwdDTO.getConfirmPassword()))
        {
            throw new UserException("新密码与确认密码不一致");
        }
        user.setPassword(userPwdDTO.getNewPassword());
        baseMapper.updateById(user);
        BaseContext.remove();
    }

    @Override
    public void logout() {
        String key = "login:token:" + BaseContext.getCurrentId();
        redisTemplate.delete(key);

        BaseContext.remove();
    }

    @Override
    public String uploadAvatar(MultipartFile file) {
        if (file == null)
        {
            throw new FileException("上传文件不能为空");
        }

        // 获取文件名和后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 生成文件名
        String fileName = UUID.randomUUID().toString() + suffix;

        String path = "D:\\avatar\\";
        File dir = new File(path);
        // 判断目录是否存在
        if (!dir.exists())
        {
            dir.mkdirs();
        }

        File newFile = new File(path + fileName);
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            return "头像上传失败";
        }

        // 构建访问url，返回给前端（被静态资源映射支持）
        String avatarUrl = "http://localhost:8080/avatar/" + fileName;

        // 更新数据库
        User user = new User();
        user.setId(BaseContext.getCurrentId());
        user.setAvatar(avatarUrl);
        baseMapper.updateById(user);

        return avatarUrl;
    }

    @Override
    public Page<UserVO> getUserPage(UserPageDTO userPageDTO) {
        Page<UserVO> page = new Page<>(userPageDTO.getCurrent(), userPageDTO.getSize());
//        LambdaQueryWrapper<UserVO> queryWrapper = new LambdaQueryWrapper<>();


        return baseMapper.getUserPage(page);
    }

    @Override
    public void assignRole(AssignRoleDTO assignRoleDTO) {
        // 删除用户角色关系
        baseMapper.deleteRole(assignRoleDTO.getUserId());


        baseMapper.assignRole(assignRoleDTO);
    }

    @Override
    public List<RoleVO> getRoleByUserId(String userId) {
        return baseMapper.getRoleByUserId(userId);
    }

}
